
package codeGenerate.json.generater;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import codeGenerate.common.freemarker.CommonFunction;
import codeGenerate.common.utils.SystemUtils;
import codeGenerate.common.vo.TemplateData;
import codeGenerate.json.tempalte.TemPathJsonAbstract;
import codeGenerate.json.vo.JavaClassVo;
import codeGenerate.json.vo.JsonConfigVo;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * json代码生成器
 * @author fudewei
 */
public class JsonGenerater {

	private JsonConfigVo configVo;

	public void generateCode() throws IOException, TemplateException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		System.out.println(">>>>>>>>>>>>>>>>>>>[" + configVo.getBeanDescription() + "]生成开始<<<<<<<<<<<<<<<<<<<");
		System.out.println(configVo);
		List<JavaClassVo> javaClassList = configVo.getJavaClassList();
		for (JavaClassVo javaClass : javaClassList) {
			SystemUtils.logIterate(javaClass.getName(), javaClass.getJavaFieldList());
		}

		Map<String, Object> root = new HashMap<String, Object>();
		//定义模板常量
		root.put("config", configVo);
		root.put("commonFunction", new CommonFunction());

		Configuration cfg = new Configuration();
		cfg.setClassicCompatible(true);
		cfg.setDirectoryForTemplateLoading(new File(configVo.getTemplateDirectory()));
		DefaultObjectWrapper objectWrapper = new DefaultObjectWrapper();
		cfg.setObjectWrapper(objectWrapper);
		//根据模版路径生成相应的代码
		Class<?> tempateClass = Class.forName(configVo.getTemplate());
		TemPathJsonAbstract temPathAbstract = (TemPathJsonAbstract) tempateClass.newInstance();
		List<TemplateData> templateDataList = temPathAbstract.getTemplateDataList(configVo);
		for (TemplateData tp : templateDataList) {
			root.put("templateData", tp.getData());
			Template temp = cfg.getTemplate(tp.getTmpPath());
			File file = new File(tp.getGenPath());
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			OutputStream writer = new FileOutputStream(new File(tp.getGenPath()));
			Writer out = new OutputStreamWriter(writer);
			temp.process(root, out);
			writer.flush();
			writer.close();
			System.out.println("模板:" + tp.getTmpPath() + "==>>生成文件==>>" + tp.getGenPath());
		}

		System.out.println(">>>>>>>>>>>>>>>>>>>表名[" + configVo.getBeanDescription() + "]生成结束<<<<<<<<<<<<<<<<<<<");
		System.out.println("\n");
	}

	public JsonConfigVo getConfigVo() {
		return configVo;
	}

	public void setConfigVo(JsonConfigVo configVo) {
		this.configVo = configVo;
	}

}
